package feizhou.untils.tools;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2019/10/18.
 */
public class GarminUtil {

    protected static Logger log = Logger.getLogger(GarminUtil.class);

    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    public static final String  consumerKey="2bd32d31-e0fc-406b-8f6c-08d97df635e9";
    public static final String  requestTokenUrl="https://connectapi.garmin.cn/oauth-service/oauth/request_token";
    public static final String  consumerSecret="Kih51iTcn0Wz6F1yGCeWehBd5pstat4B8nO";
    public static final String  accessTokenUrl="https://connectapi.garmin.cn/oauth-service/oauth/access_token";
    public static final String  garminApiBaseUrl="https://gcs-wellness.garmin.cn/wellness-api/rest/" ;


    public static String genHMAC(String data, String key) {
        byte[] result = null;
        try {
            if(StringUtil.isEmpty(key)){
                key=consumerSecret+"&";
            }
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            //用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = Base64.encodeBase64(rawHmac);

        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(),e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(),e);
        }
        if (null != result) {
            return new String(result);
        } else {
            return null;
        }
    }

    public static String getSignature(String url, Map<String, Object> parm,String reqMethodType,String hmac_key){
        try {
            StringBuilder baseStr=new StringBuilder(URLEncoder.encode(url,"utf-8"));
            String and=URLEncoder.encode("&");
            String eq=URLEncoder.encode("=");
            int i=0;
            StringBuilder first=new StringBuilder();
            parm.entrySet().stream().forEach(
                    p->{
                        if(first.length()==0){
                            baseStr.append("&");
                            first.append("&");
                        }else{
                            baseStr.append(and);
                        }
                        baseStr.append(p.getKey()).append(eq).append(p.getValue());
                    }
            );
            String encodeBaseStr=reqMethodType.toUpperCase()+"&"+baseStr;
            String info=genHMAC(encodeBaseStr,hmac_key);
            log.error("getSignature-->"+info);
            return URLEncoder.encode(info);
        }catch (Exception e){
            log.error("getSignature",e);
        }
        return null;
    }


    public static String send(String queryUrl,String signatureUrl, Map<String, Object> parm,String reqMethodType,String hmac_key){
        try {
            String signature=getSignature(signatureUrl,parm,reqMethodType,hmac_key);
            StringBuilder headUrl=new StringBuilder("OAuth ");
            parm.entrySet().stream().forEach(
                    p->{
                        headUrl.append(p.getKey()).append("=\"").append(p.getValue()).append("\"").append(",");
                    }
            );
            headUrl.append("oauth_signature=").append("\"").append(signature).append("\"");
            if(reqMethodType.toUpperCase().equals("GET")){
                return HttpGet(queryUrl,headUrl.toString());
            }else{
                return HttpPost(queryUrl,headUrl.toString());
            }
        }catch (Exception e){
            log.error("send",e);
        }
        return null ;
    }





    static class SSLClient extends DefaultHttpClient {
        public SSLClient() throws Exception {
            super();
            SSLContext ctx = SSLContext.getInstance("TLSv1.2");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        }
    }
    public static String HttpPost(String url,String headValue) {
        try {
            DefaultHttpClient httpclient =new SSLClient();
            HttpPost httpost = new HttpPost(url);
            httpost.addHeader("Authorization",headValue);
            org.apache.http.HttpResponse response = httpclient.execute(httpost);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                String returndata = EntityUtils.toString(response.getEntity());
                return returndata;
            }else{
                log.error("HttpPost-->"+EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("HttpPost",e);
        }
        return null;
    }

    public static String HttpGet(String url,String headValue) {
        try {
            DefaultHttpClient httpclient =new SSLClient();
            HttpGet httpost = new HttpGet(url);
            httpost.addHeader("Authorization",headValue);
            org.apache.http.HttpResponse response = httpclient.execute(httpost);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                String returndata = EntityUtils.toString(response.getEntity());
                return returndata;
            }else{
                log.error("HttpGet-->"+EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error("HttpGet",e);
        }
        return null;
    }

    public static String getRannum(){
        Random random=new Random();
        int rannum= (int)(random.nextDouble()*(999999999-100000000 + 1))+ 100000000;
        return String.valueOf("2"+rannum);
    }

    public static String getTimestamp(){
        return String.valueOf(System.currentTimeMillis()/1000);
    }

    public static void main(String[] args) {
        String n="1571969868";
        String b="2140469359";
        System.out.println(getTimestamp());
        System.out.println(getRannum());
    }
}
